package com.david.avcodec.system

import android.app.Activity
import android.media.MediaPlayer
import android.media.MediaRecorder
import android.os.Build
import android.os.Bundle
import android.view.View
import com.david.avcodec.R
import java.io.IOException

//https://developer.android.google.cn/guide/topics/media/mediarecorder?hl=zh-cn
//https://blog.csdn.net/sjdjdjdjahd/article/details/106037834
class MyAudioMediaRecorderActivity: Activity() {
	private var mediaRecorder: MediaRecorder? = null

    private var mediaPlayer: MediaPlayer? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_audio)

        mediaRecorder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            MediaRecorder(this)
        } else {
            MediaRecorder()
        }
        mediaRecorder?.setAudioSource(MediaRecorder.AudioSource.MIC)
        mediaRecorder?.setOutputFile("${externalCacheDir}/testfile.aac")
        mediaRecorder?.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS)
        mediaRecorder?.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)

        findViewById<View>(R.id.start).setOnClickListener {
            try {
                mediaRecorder?.prepare()
            } catch (e: IOException) {
                e.printStackTrace()
            }
           mediaRecorder?.start()
        }

        findViewById<View>(R.id.stop).setOnClickListener {
            mediaRecorder?.stop()
            mediaRecorder?.release()
        }

        mediaPlayer = MediaPlayer()
        mediaPlayer?.setDataSource("${externalCacheDir}/testfile.aac")
        findViewById<View>(R.id.start_play).setOnClickListener {
            mediaPlayer?.prepare()
            mediaPlayer?.start()
        }

        findViewById<View>(R.id.stop_play).setOnClickListener {
            mediaPlayer?.stop()
            mediaPlayer?.release()
        }
    }
}